package com.cg.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @ClassName DateUtils
 * @Description 时间日期工具类
 * @Author CG
 * @Date 2024/1/8 10:44
 **/
public class DateUtils {
    private static final Logger logger = LoggerFactory.getLogger(DateUtils.class);

    /**
     * 获取一个时间段内的日期列表
     */
    public static List<String> getDay(String startDate,String endDate) throws ParseException {
        List<String> list = new ArrayList<String>();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar startC = Calendar.getInstance();
        startC.setTime(dateFormat.parse(startDate));

        Calendar endC = Calendar.getInstance();
        endC.setTime(dateFormat.parse(endDate));
        startC.before(endC);
        while (startC.before(endC)){
            Date startD = startC.getTime();//日历转日期
            String startStr = dateFormat.format(startD);//日期转字符串
            list.add(startStr);
            startC.add(Calendar.DAY_OF_YEAR,1);
        }
        list.add(endDate);
        return list;
    }


    /**
     * 根据年月日日期计算年龄
     */
    public static Integer getAgeByBirthday(String birthday) throws ParseException {

        logger.info("计算传输生日:"+birthday);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String nowDate = simpleDateFormat.format(date);
        logger.info("当前日期:"+nowDate);
        //计算年份差
        Calendar calendar = Calendar.getInstance();

        Calendar calendarNow = Calendar.getInstance();
        calendarNow.setTime(simpleDateFormat.parse(nowDate));
        calendar.setTime(simpleDateFormat.parse(birthday));
        int birthYear = calendar.get(Calendar.YEAR);
        int nowYear = calendarNow.get(Calendar.YEAR);
        int age = nowYear - birthYear;
        logger.info("生日的年:"+birthYear+"，当前年份:"+nowYear);
        logger.info("年份差值:"+age);
        // 如果当前月份小于出生月份，或者当前月份等于出生月份但是当前日期小于出生日期，则年龄减1
        //月份
        //输入的生日的月份
        int birthMonth = calendar.get(Calendar.MONTH);
        //当前的月份
        int nowMonth = calendarNow.get(Calendar.MONTH);
        //生日的天
        int birthDay = calendar.get(Calendar.DAY_OF_MONTH);
        //当前天
        int nowDay = calendarNow.get(Calendar.DAY_OF_MONTH);
        if (nowMonth < birthMonth || (nowMonth == birthMonth && nowDay < birthDay)) {
            age--;
        }
        return age;
    }

}
